<?php

declare(strict_types=1);

namespace Plugin\Attractions\HaiKang\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\HaiKang\Model\HkDeviceGroup;

class DeviceGroupRepository extends IRepository
{
    public function __construct(protected readonly HkDeviceGroup $model) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'groupID'), static function (Builder $query, $group_id) {
                $query->whereIn('group_id', Arr::wrap($group_id));
            })
            ->when(Arr::get($params, 'groupName'), static function (Builder $query, $group_name) {
                $query->where('group_name', 'like', "%{$group_name}%");
            })
            ->when(Arr::get($params, 'groupNo'), static function (Builder $query, $group_no) {
                $query->whereIn('group_no', Arr::wrap($group_no));
            })
            ->when(Arr::get($params, 'parentID'), static function (Builder $query, $parent_id) {
                $query->whereIn('parent_id', Arr::wrap($parent_id));
            });
    }

    public function list(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->get([
                'group_id',
                'group_name',
                'group_no',
                'parent_id'
            ]);
    }

    public function listGroupAndDevice(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->with('devices')
            ->get([
                'group_id',
                'group_name',
                'group_no',
                'parent_id',
                'devices.device_id',
                'devices.device_model',
                'devices.device_name',
                'devices.device_serial',
                'devices.device_status',
                'devices.is_encrypt',
                'devices.device_version',
                'devices.defence'
            ]);
    }
}
